<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心 - 城会玩</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary: #FF6B35;
            --primary-light: #FF9B6B;
            --primary-dark: #E55A2B;
            --secondary: #2A9D8F;
            --secondary-light: #5ABFAD;
            --light: #F8F9FA;
            --dark: #343A40;
            --dark-light: #495057;
            --accent: #E9C46A;
            --success: #28a745;
            --warning: #ffc107;
            --danger: #dc3545;
            --gray-100: #f8f9fa;
            --gray-200: #e9ecef;
            --gray-300: #dee2e6;
            --gray-400: #ced4da;
            --gray-500: #adb5bd;
            --gray-600: #6c757d;
            --gray-700: #495057;
            --gray-800: #343a40;
            --gray-900: #212529;
        }

        * {
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4e8ed 100%);
            color: var(--gray-800);
            line-height: 1.6;
            min-height: 100vh;
        }

        /* 导航栏样式 */
        .navbar-brand {
            font-weight: 700;
            font-size: 1.8rem;
            color: var(--primary) !important;
            text-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            border: none;
            box-shadow: 0 4px 10px rgba(255, 107, 53, 0.3);
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, var(--primary-light), var(--primary));
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(255, 107, 53, 0.4);
        }

        /* 个人中心页面特定样式 */
        .profile-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .profile-header {
            background: white;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
            padding: 30px;
            margin-bottom: 30px;
            position: relative;
            overflow: hidden;
            border: 1px solid rgba(255,255,255,0.8);
            backdrop-filter: blur(10px);
        }

        .profile-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 5px;
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            box-shadow: 0 2px 10px rgba(42, 157, 143, 0.3);
        }

        .profile-avatar {
            width: 130px;
            height: 130px;
            border-radius: 50%;
            object-fit: cover;
            border: 5px solid white;
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
            cursor: pointer;
            transition: all 0.4s ease;
            background: linear-gradient(135deg, var(--primary-light), var(--secondary-light));
        }

        .profile-avatar:hover {
            transform: scale(1.08);
            box-shadow: 0 12px 30px rgba(0,0,0,0.2);
        }

        .profile-username {
            font-weight: 800;
            font-size: 2rem;
            margin-bottom: 5px;
            color: var(--dark);
            text-shadow: 0 1px 2px rgba(0,0,0,0.05);
        }

        .profile-bio {
            color: var(--gray-600);
            margin-bottom: 20px;
            font-size: 1.1rem;
            max-width: 80%;
        }

        .profile-stats {
            display: flex;
            gap: 30px;
            margin-top: 20px;
            flex-wrap: wrap;
        }

        .stat-item {
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            padding: 10px 15px;
            border-radius: 15px;
            background: rgba(255,255,255,0.7);
            box-shadow: 0 4px 15px rgba(0,0,0,0.05);
            min-width: 100px;
        }

        .stat-item:hover {
            transform: translateY(-5px);
            background: white;
            box-shadow: 0 8px 20px rgba(0,0,0,0.1);
        }

        .stat-number {
            font-weight: 800;
            font-size: 2rem;
            color: var(--primary);
            display: block;
            text-shadow: 0 1px 2px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }

        .stat-number.updated {
            transform: scale(1.2);
            color: var(--secondary);
        }

        .stat-label {
            font-size: 0.9rem;
            color: var(--gray-600);
            margin-top: 5px;
            font-weight: 500;
        }

        /* 侧边栏样式 */
        .profile-sidebar {
            background: white;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
            padding: 0;
            overflow: hidden;
            border: 1px solid rgba(255,255,255,0.8);
            backdrop-filter: blur(10px);
        }

        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar-menu-item {
            padding: 18px 25px;
            border-bottom: 1px solid var(--gray-200);
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            font-weight: 500;
            position: relative;
            overflow: hidden;
        }

        .sidebar-menu-item:last-child {
            border-bottom: none;
        }

        .sidebar-menu-item:hover {
            background: linear-gradient(90deg, rgba(255,107,53,0.05), transparent);
            color: var(--primary);
            padding-left: 30px;
        }

        .sidebar-menu-item.active {
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            color: white;
            box-shadow: inset 5px 0 0 rgba(255,255,255,0.5);
        }

        .sidebar-menu-item.active::after {
            content: '';
            position: absolute;
            right: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 0;
            height: 0;
            border-top: 10px solid transparent;
            border-bottom: 10px solid transparent;
            border-right: 10px solid white;
        }

        .sidebar-menu-item i {
            margin-right: 12px;
            width: 20px;
            text-align: center;
            font-size: 1.1rem;
        }

        /* 内容区域样式 */
        .profile-content {
            background: white;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
            padding: 30px;
            min-height: 600px;
            border: 1px solid rgba(255,255,255,0.8);
            backdrop-filter: blur(10px);
        }

        .content-section {
            display: none;
            animation: fadeIn 0.5s ease-in;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(15px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .content-section.active {
            display: block;
        }

        .section-title {
            font-weight: 700;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 3px solid;
            border-image: linear-gradient(90deg, var(--primary), var(--secondary)) 1;
            font-size: 1.6rem;
            color: var(--dark);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .section-title i {
            margin-right: 10px;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        /* 用户卡片样式 */
        .user-card {
            display: flex;
            align-items: center;
            padding: 20px;
            border-radius: 15px;
            margin-bottom: 15px;
            background: white;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            border: 1px solid var(--gray-200);
            transition: all 0.3s ease;
            opacity: 1;
            transform: translateY(0);
        }

        .user-card.removing {
            opacity: 0;
            transform: translateY(-20px);
            margin-bottom: 0;
            padding-top: 0;
            padding-bottom: 0;
            height: 0;
            overflow: hidden;
        }

        .user-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
            border-color: var(--primary-light);
        }

        .user-avatar {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 20px;
            border: 3px solid var(--primary);
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .user-card:hover .user-avatar {
            transform: scale(1.05);
            box-shadow: 0 6px 15px rgba(0,0,0,0.15);
        }

        .user-info {
            flex-grow: 1;
        }

        .user-name {
            font-weight: 700;
            margin-bottom: 5px;
            font-size: 1.2rem;
            color: var(--dark);
            cursor: pointer;
        }

        .user-bio {
            color: var(--gray-600);
            font-size: 0.95rem;
            margin-bottom: 5px;
            line-height: 1.4;
        }

        .user-meta {
            color: var(--gray-500);
            font-size: 0.85rem;
        }

        /* 空状态样式 */
        .empty-state {
            text-align: center;
            padding: 80px 20px;
            color: var(--gray-600);
        }

        .empty-state i {
            font-size: 5rem;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-bottom: 20px;
            opacity: 0.7;
        }

        .empty-state h4 {
            margin-bottom: 15px;
            color: var(--gray-600);
            font-weight: 600;
        }

        .empty-state p {
            margin-bottom: 25px;
            font-size: 1.1rem;
        }

        /* 加载状态 */
        .loading-spinner {
            text-align: center;
            padding: 60px 20px;
        }

        .spinner-border {
            width: 3rem;
            height: 3rem;
            border-width: 0.3em;
        }

        /* 兴趣标签样式 */
        .interests-container {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            margin-top: 10px;
        }

        .interest-tag {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            padding: 10px 18px;
            border-radius: 25px;
            font-size: 0.95rem;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(255, 107, 53, 0.3);
        }

        .interest-tag:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 15px rgba(255, 107, 53, 0.4);
        }

        .interest-tag i {
            margin-right: 8px;
            font-size: 0.9rem;
        }

        /* 头像上传相关样式 */
        .avatar-upload-container {
            position: relative;
            display: inline-block;
        }

        .avatar-upload-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(135deg, rgba(255,107,53,0.7), rgba(42,157,143,0.7));
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .avatar-upload-container:hover .avatar-upload-overlay {
            opacity: 1;
        }

        .avatar-upload-text {
            color: white;
            font-size: 0.9rem;
            text-align: center;
            font-weight: 600;
        }

        /* 消息提示 */
        .alert-message {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            min-width: 300px;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.15);
            animation: slideInRight 0.5s ease, fadeOut 0.5s ease 2.5s forwards;
        }

        @keyframes slideInRight {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }

        @keyframes fadeOut {
            from { opacity: 1; }
            to { opacity: 0; visibility: hidden; }
        }

        /* 表单样式 */
        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-label {
            font-weight: 600;
            color: var(--gray-700);
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
        }

        .form-label i {
            margin-right: 8px;
            color: var(--primary);
        }

        .form-control {
            border: 1px solid var(--gray-300);
            border-radius: 10px;
            padding: 12px 15px;
            font-size: 1rem;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 0.2rem rgba(255, 107, 53, 0.25);
        }

        /* 活动卡片样式 */
        .activity-card {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            border: 1px solid var(--gray-200);
            transition: all 0.3s ease;
            margin-bottom: 25px;
        }

        .activity-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }

        .activity-image {
            height: 180px;
            background-size: cover;
            background-position: center;
            position: relative;
        }

        .activity-category {
            position: absolute;
            top: 15px;
            left: 15px;
            background: rgba(255,255,255,0.9);
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            color: var(--primary);
        }

        .activity-status {
            position: absolute;
            top: 15px;
            right: 15px;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            color: white;
        }

        .activity-status.cancelled {
            background: var(--danger);
        }

        .activity-status.completed {
            background: var(--success);
        }

        .activity-details {
            padding: 20px;
        }

        .activity-title {
            font-weight: 700;
            font-size: 1.3rem;
            margin-bottom: 10px;
            color: var(--dark);
        }

        .activity-meta {
            display: flex;
            gap: 15px;
            margin-bottom: 10px;
            color: var(--gray-600);
            font-size: 0.9rem;
        }

        .activity-meta span {
            display: flex;
            align-items: center;
        }

        .activity-meta i {
            margin-right: 5px;
        }

        .activity-description {
            color: var(--gray-600);
            margin-bottom: 15px;
            line-height: 1.5;
        }

        .activity-participants {
            color: var(--gray-500);
            font-size: 0.9rem;
        }

        /* 模态框用户信息样式 */
        .modal-user-avatar {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            object-fit: cover;
            border: 5px solid white;
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
            margin: 0 auto 20px;
            display: block;
        }

        .modal-user-name {
            text-align: center;
            font-weight: 700;
            font-size: 1.8rem;
            margin-bottom: 10px;
            color: var(--dark);
        }

        .modal-user-bio {
            text-align: center;
            color: var(--gray-600);
            margin-bottom: 20px;
            font-size: 1.1rem;
        }

        .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 20px;
        }

        .info-item {
            background: var(--gray-100);
            padding: 15px;
            border-radius: 10px;
            text-align: center;
        }

        .info-label {
            font-weight: 600;
            color: var(--gray-700);
            margin-bottom: 5px;
            font-size: 0.9rem;
        }

        .info-value {
            color: var(--dark);
            font-weight: 500;
        }

        /* 响应式调整 */
        @media (max-width: 992px) {
            .profile-bio {
                max-width: 100%;
            }

            .profile-stats {
                gap: 15px;
            }

            .stat-item {
                min-width: 80px;
                padding: 8px 12px;
            }

            .stat-number {
                font-size: 1.6rem;
            }
        }

        @media (max-width: 768px) {
            .profile-container {
                padding: 15px;
            }

            .profile-header {
                padding: 20px;
            }

            .profile-avatar {
                width: 100px;
                height: 100px;
            }

            .profile-username {
                font-size: 1.6rem;
            }

            .profile-stats {
                justify-content: space-around;
                gap: 10px;
            }

            .stat-item {
                flex: 0 0 45%;
                margin-bottom: 15px;
            }

            .user-card {
                flex-direction: column;
                text-align: center;
                padding: 25px 20px;
            }

            .user-avatar {
                margin-right: 0;
                margin-bottom: 15px;
            }

            .activity-meta {
                flex-direction: column;
                gap: 5px;
            }
        }

        @media (max-width: 576px) {
            .profile-content {
                padding: 20px;
            }

            .section-title {
                font-size: 1.4rem;
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }

            .stat-item {
                flex: 0 0 100%;
            }

            .empty-state {
                padding: 60px 15px;
            }

            .empty-state i {
                font-size: 4rem;
            }
        }


        /* ========== 新增活动卡片样式 ========== */
        .activity-card {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid var(--gray-200);
            transition: all 0.3s ease;
            height: 100%;
        }

        .activity-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
        }

        .activity-image {
            height: 200px;
            background-size: cover;
            background-position: center;
            position: relative;
        }

        .activity-category {
            position: absolute;
            top: 15px;
            left: 15px;
            background: rgba(255,255,255,0.9);
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            color: var(--primary);
        }

        .activity-status {
            position: absolute;
            top: 15px;
            right: 15px;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            color: white;
        }

        .activity-participation-status {
            position: absolute;
            bottom: 15px;
            right: 15px;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            color: white;
            background: var(--secondary);
        }

        /* 状态颜色 */
        .status-draft {
            background: var(--gray-500);
        }

        .status-pending {
            background: var(--warning);
        }

        .status-published {
            background: var(--success);
        }

        .status-cancelled {
            background: var(--danger);
        }

        .status-completed {
            background: var(--secondary);
        }

        .participation-attended {
            background: var(--success);
        }

        .participation-cancelled {
            background: var(--danger);
        }

        .activity-details {
            padding: 20px;
        }

        .activity-title {
            font-weight: 700;
            font-size: 1.3rem;
            margin-bottom: 10px;
            color: var(--dark);
            line-height: 1.3;
        }

        .activity-meta {
            display: flex;
            flex-direction: column;
            gap: 8px;
            margin-bottom: 15px;
            color: var(--gray-600);
            font-size: 0.9rem;
        }

        .activity-meta span {
            display: flex;
            align-items: center;
        }

        .activity-meta i {
            margin-right: 8px;
            width: 16px;
            text-align: center;
        }

        .activity-description {
            color: var(--gray-600);
            margin-bottom: 15px;
            line-height: 1.5;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .activity-actions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .activity-actions .btn {
            flex: 1;
            min-width: 120px;
            font-size: 0.85rem;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .activity-image {
                height: 160px;
            }

            .activity-actions {
                flex-direction: column;
            }

            .activity-actions .btn {
                min-width: auto;
            }
        }

        /* 删除私信相关的样式，因为已经独立到talking.html */
    </style>
</head>
<body>
{% load static %}
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm sticky-top">
        <div class="container">
            <a class="navbar-brand" href="/meet/index/">
                <i class="fas fa-map-marker-alt me-2"></i>城会玩
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/meet/index/">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/meet/active/">发现活动</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/meet/create_activity/">创建活动</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/meet/social/">社区</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/user/talking/">聊天</a>
                    </li>
                </ul>
                <div class="d-flex">
                    <a href="/user/logout/" class="btn btn-outline-primary">
                        <i class="fas fa-sign-out-alt me-2"></i>退出登录
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <!-- 个人中心主体内容 -->
    <div class="profile-container">
        <!-- 个人信息头部 -->
        <div class="profile-header">
            <div class="row align-items-center">
                <div class="col-md-3 text-center">
                    <!-- 头像上传区域 -->
                    <div class="avatar-upload-container">
                        <img id="header-avatar"
                             src="{{ avatar_url }}"
                             alt="用户头像" class="profile-avatar"
                             onerror="this.onerror=null; this.src='{% static 'images/default-avatar.png' %}'">
                        <div class="avatar-upload-overlay" onclick="document.getElementById('avatar-input').click()">
                            <div class="avatar-upload-text">
                                <i class="fas fa-camera fa-2x mb-2"></i><br>
                                更换头像
                            </div>
                        </div>
                    </div>
                    <!-- 隐藏的文件输入 -->
                    <input type="file" id="avatar-input" accept="image/*" style="display: none;" onchange="handleAvatarUpload(this.files[0])">
                </div>
                <div class="col-md-6">
                    <h1 class="profile-username">{{ user.username }}</h1>
                    <p class="profile-bio">{{ user.bio|default:"这个用户很懒，还没有写个人简介..." }}</p>
                    <!-- 统计信息 -->
                    <div class="profile-stats">
                        <div class="stat-item" data-target="my-activities">
                            <span class="stat-number">{{ organized_count }}</span>
                            <span class="stat-label">发布活动</span>
                        </div>
                        <div class="stat-item" data-target="joined-activities">
                            <span class="stat-number">{{ joined_count }}</span>
                            <span class="stat-label">参与活动</span>
                        </div>
                        <div class="stat-item" data-target="following">
                            <span class="stat-number">{{ following_count }}</span>
                            <span class="stat-label">关注</span>
                        </div>
                        <div class="stat-item" data-target="followers">
                            <span class="stat-number">{{ followers_count }}</span>
                            <span class="stat-label">粉丝</span>
                        </div>
                    </div>
                </div>
                <div class="col-md-3 text-end">
                    <!-- 编辑资料按钮已移除，功能移至账户设置 -->
                </div>
            </div>
        </div>

        <div class="row">
            <!-- 侧边栏导航 -->
            <div class="col-md-3">
                <div class="profile-sidebar">
                    <ul class="sidebar-menu">
                        <!-- 设置账户设置为默认激活状态 -->
                        <li class="sidebar-menu-item active" data-target="settings">
                            <i class="fas fa-cog"></i>账户设置
                        </li>
                        <li class="sidebar-menu-item" data-target="my-activities">
                            <i class="fas fa-calendar-alt"></i>我发布的活动
                        </li>
                        <li class="sidebar-menu-item" data-target="joined-activities">
                            <i class="fas fa-users"></i>我参与的活动
                        </li>
                        <li class="sidebar-menu-item" data-target="following">
                            <i class="fas fa-user-plus"></i>我的关注
                        </li>
                        <li class="sidebar-menu-item" data-target="followers">
                            <i class="fas fa-user-friends"></i>我的粉丝
                        </li>
                    </ul>
                </div>
            </div>

            <!-- 内容区域 -->
            <div class="col-md-9">
                <div class="profile-content">
                    <!-- 账户设置部分 -->
                    <div id="settings" class="content-section active">
                        <h3 class="section-title"><i class="fas fa-cogs"></i>账户设置</h3>
                        <form id="profile-form">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label"><i class="fas fa-user"></i>用户名</label>
                                        <input type="text" class="form-control" name="username" value="{{ user.username }}" required>
                                    </div>
                                    <!-- 注册时间显示 -->
                                    <div class="form-group">
                                        <label class="form-label"><i class="fas fa-calendar-plus"></i>注册时间</label>
                                        <div class="registration-time-display p-3 rounded">
                                            <div class="d-flex align-items-center justify-content-between">
                                                <div>
                                                    <i class="fas fa-calendar-check text-primary me-2"></i>
                                                    <span class="fw-bold">{{ user.date_joined|date:"Y年m月d日" }}</span>
                                                </div>
                                                <div class="text-muted small">
                                                    <i class="fas fa-clock me-1"></i>
                                                    {{ user.date_joined|date:"H:i" }}
                                                </div>
                                            </div>
                                            <div class="mt-2 text-center">
                                                <span class="badge bg-primary bg-opacity-10 text-primary">
                                                    <i class="fas fa-user-plus me-1"></i>
                                                    已加入 {{ user.date_joined|timesince }}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <!-- 邮箱和手机号 -->
                                    <div class="form-group">
                                        <label class="form-label"><i class="fas fa-envelope"></i>邮箱</label>
                                        <input type="email" class="form-control" name="email" value="{{ user.email }}" required>
                                    </div>
                                    <div class="form-group">
                                        <label class="form-label"><i class="fas fa-phone"></i>手机号</label>
                                        <input type="tel" class="form-control" name="phone" value="{{ user.phone|default:'' }}">
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="form-label"><i class="fas fa-tags"></i>兴趣标签</label>
                                <input type="text" class="form-control" name="interests"
                                       placeholder="请输入兴趣标签，用逗号分隔"
                                       value="{% if user.interests %}{{ user.interests|join:"," }}{% endif %}">
                                <small class="form-text text-muted">多个兴趣请用逗号分隔，例如：摄影,旅行,美食</small>
                            </div>
                            <div class="form-group">
                                <label class="form-label"><i class="fas fa-edit"></i>个性签名</label>
                                <textarea class="form-control" name="bio" rows="3" placeholder="介绍一下自己...">{{ user.bio|default:'' }}</textarea>
                            </div>
                            <div class="mt-4">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save me-2"></i>保存更改
                                </button>
                                <button type="button" class="btn btn-outline-primary ms-2" onclick="resetForm()">
                                    <i class="fas fa-undo me-2"></i>重置
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- 我发布的活动 -->
                    <div id="my-activities" class="content-section">
                        <div class="loading-spinner">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                            <p class="mt-2">正在加载活动数据...</p>
                        </div>
                    </div>

                    <!-- 我参与的活动 -->
                    <div id="joined-activities" class="content-section">
                        <div class="loading-spinner">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                            <p class="mt-2">正在加载参与活动数据...</p>
                        </div>
                    </div>

                    <!-- 我的关注 -->
                    <div id="following" class="content-section">
                        <div class="loading-spinner">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                            <p class="mt-2">正在加载关注列表...</p>
                        </div>
                    </div>

                    <!-- 我的粉丝 -->
                    <div id="followers" class="content-section">
                        <div class="loading-spinner">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                            <p class="mt-2">正在加载粉丝列表...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 消息提示容器 -->
    <div id="message-container"></div>

    <!-- 用户信息模态框 -->
    <div class="modal fade" id="userInfoModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">用户信息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <img id="modal-user-avatar" src="" alt="用户头像" class="modal-user-avatar">
                    <div class="modal-user-info">
                        <h3 id="modal-user-name" class="modal-user-name"></h3>
                        <p id="modal-user-bio" class="modal-user-bio"></p>
                    </div>
                    <div class="info-grid">
                        <div class="info-item">
                            <div class="info-label">邮箱</div>
                            <div id="modal-user-email" class="info-value"></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">注册时间</div>
                            <div id="modal-user-registration" class="info-value"></div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="info-label text-center mb-2">兴趣标签</div>
                        <div id="modal-user-interests" class="interests-container justify-content-center"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量 - 移除私信相关的全局变量
        // 只保留个人中心需要的功能
        /**
         * 初始化页面功能
         */
        document.addEventListener('DOMContentLoaded', function() {
            initializePage();
             // 为所有活动图片设置错误处理
                document.querySelectorAll('.activity-cover').forEach(cover => {
                    const bgImage = cover.style.backgroundImage;
                    if (bgImage && bgImage.includes('url')) {
                        // 创建一个临时图片来检查URL是否有效
                        const tempImg = new Image();
                        tempImg.src = bgImage.replace(/url\(['"]?(.*?)['"]?\)/i, '$1');
                        tempImg.onerror = function() {
                            cover.style.backgroundImage = 'url(https://res.cloudinary.com/dqfqah1dn/image/upload/v1640997659/meetlocal/default-activity_zkvqjp.jpg)';
                        };
                    }
                });
        });

        function initializePage() {
            // 菜单切换功能
            setupMenuNavigation();

            // 统计项点击功能
            setupStatItems();

            // 表单提交功能
            setupFormSubmission();
        }

        /**
         * 设置菜单导航功能
         */
        function setupMenuNavigation() {
            const menuItems = document.querySelectorAll('.sidebar-menu-item');
            const contentSections = document.querySelectorAll('.content-section');

            menuItems.forEach(item => {
                item.addEventListener('click', function() {
                    const targetId = this.getAttribute('data-target');
                    console.log(`菜单点击: 切换到 ${targetId}`);

                    // 更新菜单激活状态
                    menuItems.forEach(menuItem => menuItem.classList.remove('active'));
                    this.classList.add('active');

                    // 更新内容区域显示
                    contentSections.forEach(section => {
                        section.classList.remove('active');
                        if (section.id === targetId) {
                            section.classList.add('active');
                        }
                    });

                    // 加载对应区域的数据（设置页面除外）
                    if (targetId !== 'settings') {
                        console.log(`加载板块数据: ${targetId}`);
                        loadSectionData(targetId);
                    }
                });
            });
        }

        /**
         * 确保头像URL是绝对路径
         * @param {string} avatarUrl - 头像URL
         * @returns {string} 处理后的头像URL
         */
        function ensureAbsoluteAvatarUrl(avatarUrl) {
            if (!avatarUrl) {
                return '{% static 'images/default-avatar.png' %}';
            }

            // 如果已经是完整URL，直接返回
            if (avatarUrl.startsWith('http://') || avatarUrl.startsWith('https://')) {
                return avatarUrl;
            }

            // 如果是Cloudinary的相对路径，添加Cloudinary域名（如果需要）
            // Cloudinary通常返回完整URL，但如果是相对路径，需要处理
            if (avatarUrl.startsWith('/')) {
                // 如果是绝对路径，添加当前域名
                return window.location.origin + avatarUrl;
            }

            // 其他情况返回默认头像
            return '{% static 'images/default-avatar.png' %}';
        }

        /**
         * 设置统计项点击功能
         */
        function setupStatItems() {
            const statItems = document.querySelectorAll('.stat-item');
            statItems.forEach(item => {
                item.addEventListener('click', function() {
                    const targetId = this.getAttribute('data-target');
                    if (targetId) {
                        // 找到对应的菜单项并触发点击
                        const menuItem = document.querySelector(`.sidebar-menu-item[data-target="${targetId}"]`);
                        if (menuItem) {
                            menuItem.click();
                        }
                    }
                });
            });
        }

        /**
         * 设置表单提交功能
         */
        function setupFormSubmission() {
            const profileForm = document.getElementById('profile-form');
            if (profileForm) {
                profileForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    updateProfile(this);
                });
            }
        }

        /**
         * 处理头像上传
         * @param {File} file - 上传的头像文件
         */
        function handleAvatarUpload(file) {
            if (!file) return;

            // 检查文件类型
            if (!file.type.startsWith('image/')) {
                showMessage('请选择图片文件！', 'warning');
                return;
            }

            // 检查文件大小（限制为5MB）
            if (file.size > 5 * 1024 * 1024) {
                showMessage('图片大小不能超过5MB！', 'warning');
                return;
            }

            const reader = new FileReader();

            reader.onload = function(e) {
                // 将图片转换为base64格式
                const base64Image = e.target.result;

                // 更新页面显示（预览）
                document.getElementById('header-avatar').src = base64Image;

                // 发送到服务器保存
                updateAvatar(base64Image);
            };

            reader.readAsDataURL(file);
        }

        /**
         * 更新头像到服务器
         * @param {string} base64Image - base64编码的图片
         */
        async function updateAvatar(base64Image) {
            try {
                showMessage('正在上传头像...', 'info');

                const response = await fetch('/user/upload_avatar/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    body: JSON.stringify({
                        avatar: base64Image
                    })
                });

                const result = await response.json();

                if (result.success) {
                    // 更新页面上的头像URL，添加时间戳防止缓存
                    const avatarElement = document.getElementById('header-avatar');
                    if (result.avatar_url) {
                        avatarElement.src = result.avatar_url + '?t=' + new Date().getTime();
                        showMessage('头像更新成功！', 'success');

                        // 同时更新其他可能显示头像的地方
                        updateAllAvatarDisplays(result.avatar_url);
                    } else {
                        showMessage('头像更新成功，但获取URL失败', 'warning');
                    }
                } else {
                    showMessage('头像更新失败: ' + result.message, 'error');
                    // 恢复原来的头像
                    resetAvatar();
                }
            } catch (error) {
                console.error('头像更新失败:', error);
                showMessage('网络错误，请重试', 'error');
                resetAvatar();
            }
        }

        /**
         * 恢复默认头像
         */
        function resetAvatar() {
            const defaultAvatar = '{% static 'images/default-avatar.png' %}';
            const avatarElement = document.getElementById('header-avatar');
            avatarElement.src = defaultAvatar + '?t=' + new Date().getTime();
        }

        /**
         * 更新所有头像显示
         */
        function updateAllAvatarDisplays(avatarUrl) {
            // 更新页面中所有显示当前用户头像的地方
            const allAvatars = document.querySelectorAll('img[src*="avatar"]');
            allAvatars.forEach(img => {
                if (img.src.includes('avatar') && !img.src.includes('default')) {
                    img.src = avatarUrl + '?t=' + new Date().getTime();
                }
            });
        }

        /**
         * 显示消息提示
         * @param {string} message - 消息内容
         * @param {string} type - 消息类型: 'success', 'error', 'warning', 'info'
         */
        function showMessage(message, type = 'info') {
            const messageContainer = document.getElementById('message-container');

            const alertClass = {
                'success': 'alert-success',
                'error': 'alert-danger',
                'warning': 'alert-warning',
                'info': 'alert-info'
            }[type] || 'alert-info';

            const iconClass = {
                'success': 'fa-check-circle',
                'error': 'fa-exclamation-circle',
                'warning': 'fa-exclamation-triangle',
                'info': 'fa-info-circle'
            }[type] || 'fa-info-circle';

            const alert = document.createElement('div');
            alert.className = `alert ${alertClass} alert-dismissible fade show alert-message`;
            alert.innerHTML = `
                <i class="fas ${iconClass} me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;

            messageContainer.appendChild(alert);

            // 自动移除消息
            setTimeout(() => {
                if (alert.parentNode) {
                    alert.parentNode.removeChild(alert);
                }
            }, 3000);
        }

        /**
         * 动态加载各部分数据
         * @param {string} sectionId - 区域ID
         */
        async function loadSectionData(sectionId) {
            console.log(`开始加载板块数据: ${sectionId}`);

            // 如果是设置页面，不需要加载数据，直接返回
            if (sectionId === 'settings') {
                console.log('设置页面，跳过数据加载');
                return;
            }

            const section = document.getElementById(sectionId);
            if (!section) {
                console.error(`找不到板块元素: ${sectionId}`);
                return;
            }

            // 显示加载状态
            section.innerHTML = `
                <div class="loading-spinner">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2">正在加载数据...</p>
                </div>
            `;

            try {
                console.log(`请求URL: /user/section_data/${sectionId}/`);
                const response = await fetch(`/user/section_data/${sectionId}/`);

                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }

                const data = await response.json();
                console.log(`收到 ${sectionId} 数据:`, data);

                // 根据不同的部分渲染数据
                if (!data.success) {
                    throw new Error(data.error || data.message || '未知错误');
                }

                switch(sectionId) {
                    case 'my-activities':
                        renderActivities(data.activities, sectionId);
                        break;
                    case 'joined-activities':
                        renderActivities(data.activities, sectionId);
                        break;
                    case 'following':
                        renderFollowingList(data.users || data.following, sectionId);
                        break;
                    case 'followers':
                        renderFollowersList(data.users || data.followers, sectionId);
                        break;
                    default:
                        section.innerHTML = '<p>未知的板块类型</p>';
                }
            } catch (error) {
                console.error(`加载 ${sectionId} 数据失败:`, error);
                section.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        数据加载失败: ${error.message}
                        <br>
                        <small>请刷新页面重试或联系管理员</small>
                    </div>
                    <div class="text-center mt-3">
                        <button class="btn btn-primary" onclick="loadSectionData('${sectionId}')">
                            <i class="fas fa-redo me-2"></i>重新加载
                        </button>
                    </div>
                `;
            }
        }

        // 渲染板块数据的通用函数
        function renderSection(section, data) {
            const sectionElement = document.getElementById(`${section}-section`);

            if (!data || data.length === 0) {
                sectionElement.innerHTML = `
                    <div class="text-center py-4">
                        <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">暂无数据</h5>
                        <p class="text-muted">这里还没有内容</p>
                    </div>
                `;
                return;
            }

            let html = '';

            if (section === 'joined-activities') {
                html = renderActivities(data);
            } else if (section === 'organized-activities') {
                html = renderOrganizedActivities(data);
            } else if (section === 'favorites') {
                html = renderFavorites(data);
            } else {
                // 默认渲染
                html = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
            }

            sectionElement.innerHTML = html;
        }

        /**
 * 渲染活动列表
 * @param {Array} activities - 活动数组
 * @param {string} sectionId - 区域ID ('my-activities' 或 'joined-activities')
 */
function renderActivities(activities, sectionId) {
    const section = document.getElementById(sectionId);
    if (!section) return;

    if (!activities || activities.length === 0) {
        let emptyMessage = '';
        let emptyIcon = '';

        if (sectionId === 'my-activities') {
            emptyMessage = '您还没有发布任何活动';
            emptyIcon = 'fa-calendar-plus';
        } else {
            emptyMessage = '您还没有参与任何活动';
            emptyIcon = 'fa-users';
        }

        section.innerHTML = `
            <h3 class="section-title">
                <i class="fas ${emptyIcon}"></i>
                ${sectionId === 'my-activities' ? '我发布的活动' : '我参与的活动'}
            </h3>
            <div class="empty-state">
                <i class="fas ${emptyIcon}"></i>
                <h4>${emptyMessage}</h4>
                <p>${sectionId === 'my-activities' ? '去创建一个有趣的活动吧！' : '去发现一些有趣的活动吧！'}</p>
                ${sectionId === 'my-activities' ?
                    '<a href="/meet/create_activity/" class="btn btn-primary mt-3"><i class="fas fa-plus me-2"></i>创建活动</a>' :
                    '<a href="/meet/active/" class="btn btn-primary mt-3"><i class="fas fa-search me-2"></i>发现活动</a>'
                }
            </div>
        `;
        return;
    }

    let html = `
        <h3 class="section-title">
            <i class="fas ${sectionId === 'my-activities' ? 'fa-calendar-alt' : 'fa-users'}"></i>
            ${sectionId === 'my-activities' ? '我发布的活动' : '我参与的活动'}
            <span class="badge bg-primary">${activities.length}</span>
        </h3>
        <div class="row" id="activities-container">
    `;

    activities.forEach(activity => {
        const statusClass = getActivityStatusClass(activity.status);
        const participationStatusClass = activity.participation_status ? getParticipationStatusClass(activity.participation_status) : '';

        html += `
            <div class="col-lg-6 col-xl-4 mb-4">
                <div class="activity-card" data-activity-id="${activity.id}">
                    <div class="activity-image" style="background-image: url('${activity.cover_image}')">
                        <div class="activity-category">${activity.category}</div>
                        <div class="activity-status ${statusClass}">${activity.status_display}</div>
                        ${activity.participation_status_display ?
                            `<div class="activity-participation-status ${participationStatusClass}">${activity.participation_status_display}</div>` :
                            ''
                        }
                    </div>
                    <div class="activity-details">
                        <h4 class="activity-title">${escapeHtml(activity.title)}</h4>
                        <div class="activity-meta">
                            <span><i class="fas fa-map-marker-alt"></i> ${activity.location_name}</span>
                            <span><i class="fas fa-clock"></i> ${activity.start_time}</span>
                            <span><i class="fas fa-users"></i> ${activity.current_participants}/${activity.max_participants}</span>
                        </div>
                        <p class="activity-description">${escapeHtml(activity.description)}</p>
                        <div class="activity-actions">
                            <a href="/meet/activity/${activity.id}/" class="btn btn-sm btn-primary">
                                <i class="fas fa-eye me-1"></i>查看详情
                            </a>
                            ${sectionId === 'my-activities' ? `
                                ${activity.can_edit ? `
                                    <a href="/meet/edit_activity/${activity.id}/" class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-edit me-1"></i>编辑
                                    </a>
                                ` : ''}
                                ${activity.can_cancel ? `
                                    <button class="btn btn-sm btn-warning" onclick="cancelActivity(${activity.id})">
                                        <i class="fas fa-times me-1"></i>取消活动
                                    </button>
                                ` : ''}
                                ${activity.can_delete ? `
                                    <button class="btn btn-sm btn-danger" onclick="deleteActivity(${activity.id})">
                                        <i class="fas fa-trash me-1"></i>删除
                                    </button>
                                ` : ''}
                            ` : ''}
                            ${sectionId === 'joined-activities' ? `
                                ${activity.can_cancel ? `
                                    <button class="btn btn-sm btn-warning" onclick="cancelParticipation(${activity.id})">
                                        <i class="fas fa-times me-1"></i>取消报名
                                    </button>
                                ` : ''}
                                ${activity.can_review ? `
                                    <button class="btn btn-sm btn-success" onclick="reviewActivity(${activity.id})">
                                        <i class="fas fa-star me-1"></i>评价活动
                                    </button>
                                ` : ''}
                            ` : ''}
                        </div>
                    </div>
                </div>
            </div>
        `;
    });

    html += `</div>`;
    section.innerHTML = html;
}

/**
 * 获取活动状态CSS类
 */
function getActivityStatusClass(status) {
    const statusMap = {
        'draft': 'status-draft',
        'pending': 'status-pending',
        'published': 'status-published',
        'cancelled': 'status-cancelled',
        'completed': 'status-completed'
    };
    return statusMap[status] || '';
}

/**
 * 取消活动
 */
async function cancelActivity(activityId) {
    if (!confirm('确定要取消这个活动吗？取消后无法恢复。')) {
        return;
    }

    try {
        showMessage('正在取消活动...', 'info');

        const response = await fetch(`/user/cancel_activity/${activityId}/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            }
        });

        const result = await response.json();

        if (result.success) {
            showMessage(result.message, 'success');
            // 重新加载活动列表
            loadSectionData('my-activities');
        } else {
            showMessage(result.message, 'error');
        }
    } catch (error) {
        console.error('取消活动失败:', error);
        showMessage('取消活动失败，请重试', 'error');
    }
}

/**
 * 删除活动
 */
async function deleteActivity(activityId) {
    if (!confirm('确定要删除这个活动吗？删除后无法恢复。')) {
        return;
    }

    try {
        showMessage('正在删除活动...', 'info');

        const response = await fetch(`/user/delete_activity/${activityId}/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            }
        });

        const result = await response.json();

        if (result.success) {
            showMessage(result.message, 'success');
            // 重新加载活动列表
            loadSectionData('my-activities');
        } else {
            showMessage(result.message, 'error');
        }
    } catch (error) {
        console.error('删除活动失败:', error);
        showMessage('删除活动失败，请重试', 'error');
    }
}

/**
 * 获取参与状态CSS类
 */
function getParticipationStatusClass(status) {
    const statusMap = {
        'registered': 'participation-registered',
        'attended': 'participation-attended',
        'cancelled': 'participation-cancelled'
    };
    return statusMap[status] || '';
}

        function getStatusClass(status) {
            const statusMap = {
                'published': 'bg-success',
                'draft': 'bg-secondary',
                'cancelled': 'bg-danger',
                'ongoing': 'bg-warning',
                'upcoming': 'bg-info',
                'ended': 'bg-dark'
            };
            return statusMap[status] || 'bg-secondary';
        }

        function formatDate(dateString) {
            if (!dateString) return '日期待定';
            try {
                const date = new Date(dateString);
                return date.toLocaleDateString('zh-CN');
            } catch (e) {
                return dateString;
            }
        }

        function escapeHtml(unsafe) {
            if (!unsafe) return '';
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        /**
         * 渲染关注列表
         * @param {Array} users - 用户数组
         * @param {string} sectionId - 区域ID
         */
        function renderFollowingList(users, sectionId) {
            const section = document.getElementById(sectionId);
            if (!section) return;

            // 确保 users 是数组
            if (!Array.isArray(users)) {
                users = [];
            }

            if (users.length === 0) {
                section.innerHTML = `
                    <h3 class="section-title"><i class="fas fa-user-plus"></i>我的关注</h3>
                    <div class="empty-state">
                        <i class="fas fa-user-plus"></i>
                        <h4>暂无关注</h4>
                        <p>您还没有关注任何用户</p>
                    </div>
                `;
                return;
            }

            let html = `
                <h3 class="section-title">
                    <i class="fas fa-user-plus"></i>我的关注
                    <span class="badge bg-primary">${users.length}</span>
                </h3>
            `;

            users.forEach(user => {
                // 处理不同的数据结构
                const userData = {
                    id: user.id || 0,
                    username: user.username || '未知用户',
                    bio: user.bio || '这个用户很懒，还没有写个人简介...',
                    avatar: user.avatar || '/static/images/default-avatar.png',
                    registration_date: user.registration_date || user.date_joined || '未知时间',
                    created_at: user.created_at || '未知时间',
                    interests: user.interests || []
                };

                // 确保头像URL是完整的
                const avatarUrl = ensureAbsoluteAvatarUrl(userData.avatar);

                html += `
                    <div class="user-card" id="following-user-${userData.id}">
                        <img src="${avatarUrl}"
                             alt="用户头像" class="user-avatar"
                             onclick="viewUserInfo(${userData.id})"
                             style="cursor: pointer;"
                             onerror="this.onerror=null; this.src='{% static 'images/default-avatar.png' %}'">
                        <div class="user-info">
                            <div class="user-name" style="cursor: pointer;" onclick="viewUserInfo(${userData.id})">
                                ${userData.username}
                            </div>
                            <div class="user-bio">${userData.bio}</div>
                            <div class="user-meta">
                                <span><i class="fas fa-calendar-plus me-1"></i>注册时间: ${userData.registration_date}</span>
                                <span class="ms-3"><i class="fas fa-heart me-1"></i>关注于: ${userData.created_at}</span>
                            </div>
                            ${userData.interests && userData.interests.length > 0 ? `
                                <div class="interests-container mt-2">
                                    ${userData.interests.map(interest =>
                                        `<span class="interest-tag"><i class="fas fa-tag"></i>${interest}</span>`
                                    ).join('')}
                                </div>
                            ` : ''}
                        </div>
                        <div class="search-user-actions">
                            <button class="btn btn-outline-primary btn-sm action-btn" onclick="toggleFollow(${userData.id})">
                                <i class="fas fa-user-minus me-1"></i>取消关注
                            </button>
                            <button class="btn btn-primary btn-sm action-btn" onclick="viewUserInfo(${userData.id})">
                                <i class="fas fa-info-circle me-1"></i>查看信息
                            </button>
                        </div>
                    </div>
                `;
            });

            section.innerHTML = html;
        }

        /**
         * 渲染粉丝列表
         * @param {Array} users - 用户数组
         * @param {string} sectionId - 区域ID
         */
        function renderFollowersList(users, sectionId) {
            const section = document.getElementById(sectionId);
            if (!section) return;

            if (!users || users.length === 0) {
                section.innerHTML = `
                    <h3 class="section-title"><i class="fas fa-user-friends"></i>我的粉丝</h3>
                    <div class="empty-state">
                        <i class="fas fa-user-friends"></i>
                        <h4>暂无粉丝</h4>
                        <p>您还没有任何粉丝</p>
                    </div>
                `;
                return;
            }

            let html = `
                <h3 class="section-title">
                    <i class="fas fa-user-friends"></i>我的粉丝
                    <span class="badge bg-primary">${users.length}</span>
                </h3>
            `;

            users.forEach(user => {
                // 确保头像URL是完整的
                const avatarUrl = ensureAbsoluteAvatarUrl(user.avatar);

                html += `
                    <div class="user-card" id="follower-user-${user.id}">
                        <img src="${avatarUrl}"
                             alt="用户头像" class="user-avatar"
                             onclick="viewUserInfo(${user.id})"
                             style="cursor: pointer;"
                             onerror="this.onerror=null; this.src='{% static 'images/default-avatar.png' %}'">
                        <div class="user-info">
                            <div class="user-name" style="cursor: pointer;" onclick="viewUserInfo(${user.id})">
                                ${user.username}
                            </div>
                            <div class="user-bio">${user.bio}</div>
                            <div class="user-meta">
                                <span><i class="fas fa-calendar-plus me-1"></i>注册时间: ${user.registration_date}</span>
                                <span class="ms-3"><i class="fas fa-heart me-1"></i>关注你于: ${user.created_at}</span>
                            </div>
                        </div>
                        <div class="search-user-actions">
                            ${user.is_following_back ?
                                `<button class="btn btn-outline-primary btn-sm action-btn" onclick="toggleFollow(${user.id})">
                                    <i class="fas fa-user-minus me-1"></i>取消关注
                                </button>` :
                                `<button class="btn btn-primary btn-sm action-btn" onclick="toggleFollow(${user.id})">
                                    <i class="fas fa-user-plus me-1"></i>关注
                                </button>`
                            }
                            <button class="btn btn-primary btn-sm action-btn" onclick="viewUserInfo(${user.id})">
                                <i class="fas fa-info-circle me-1"></i>查看信息
                            </button>
                        </div>
                    </div>
                `;
            });

            section.innerHTML = html;
        }

        /**
         * 更新用户资料
         * @param {HTMLFormElement} form - 表单元素
         */
        async function updateProfile(form) {
            const formData = new FormData(form);
            const data = Object.fromEntries(formData.entries());

            // 处理兴趣标签，转换为数组
            if (data.interests) {
                data.interests = data.interests.split(',').map(interest => interest.trim()).filter(interest => interest);
            }

            try {
                const response = await fetch('/user/update_profile/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    body: JSON.stringify(data)
                });

                const result = await response.json();

                if (result.success) {
                    showMessage('资料更新成功！', 'success');
                    // 更新页面显示
                    updateProfileDisplay(result.user, result.profile);
                } else {
                    showMessage('更新失败: ' + result.message, 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showMessage('网络错误，请重试', 'error');
            }
        }

        /**
         * 更新页面显示
         * @param {Object} userData - 用户数据
         * @param {Object} profileData - 档案数据
         */
        function updateProfileDisplay(userData, profileData) {
            // 更新头部信息
            const usernameElement = document.querySelector('.profile-username');
            const bioElement = document.querySelector('.profile-bio');
            const headerAvatar = document.getElementById('header-avatar');

            if (usernameElement && userData.username) {
                usernameElement.textContent = userData.username;
            }

            if (bioElement && userData.bio) {
                bioElement.textContent = userData.bio;
            }

            if (headerAvatar && userData.avatar_url) {
                headerAvatar.src = userData.avatar_url;
            }
        }

        /**
         * 重置表单到初始值
         */
        function resetForm() {
            // 重新加载页面数据
            location.reload();
        }

        /**
         * 获取活动状态CSS类
         * @param {string} status - 活动状态
         * @returns {string} CSS类名
         */
        function getActivityStatusClass(status) {
            const statusMap = {
                'draft': '',
                'published': '',
                'cancelled': 'cancelled',
                'completed': 'completed',
                'registered': '',
                'attended': 'completed'
            };
            return statusMap[status] || '';
        }

        /**
         * 获取活动状态文本
         * @param {string} status - 活动状态
         * @returns {string} 状态文本
         */
        function getActivityStatusText(status) {
            const statusMap = {
                'draft': '草稿',
                'published': '进行中',
                'cancelled': '已取消',
                'completed': '已完成',
                'registered': '已报名',
                'attended': '已参加'
            };
            return statusMap[status] || status;
        }

        /**
         * 获取CSRF token
         * @param {string} name - cookie名称
         * @returns {string} cookie值
         */
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        // 关注/取消关注功能
        async function toggleFollow(userId) {
            try {
                const response = await fetch('/user/toggle_follow/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    body: JSON.stringify({ user_id: userId })
                });

                const result = await response.json();

                if (result.success) {
                    showMessage(result.message, 'success');

                    // 更新统计数字
                    if (result.stats) {
                        updateFollowStats(result.stats);
                    }

                    // 获取当前活跃的部分
                    const activeSection = document.querySelector('.content-section.active').id;

                    if (activeSection === 'following') {
                        // 在关注列表中，移除该用户卡片
                        removeUserCard(userId, 'following');
                    } else if (activeSection === 'followers') {
                        // 在粉丝列表中，重新加载以更新关注状态
                        loadSectionData('followers');
                    }
                } else {
                    showMessage(result.message, 'error');
                }
            } catch (error) {
                console.error('操作失败:', error);
                showMessage('操作失败，请重试', 'error');
            }
        }

        /**
         * 更新关注统计数字
         * @param {Object} stats - 统计信息
         */
        function updateFollowStats(stats) {
            // 更新关注数
            const followingStat = document.querySelector('.stat-item[data-target="following"] .stat-number');
            if (followingStat && stats.following_count !== undefined) {
                followingStat.textContent = stats.following_count;
                followingStat.classList.add('updated');
                setTimeout(() => {
                    followingStat.classList.remove('updated');
                }, 300);
            }

            // 更新粉丝数
            const followersStat = document.querySelector('.stat-item[data-target="followers"] .stat-number');
            if (followersStat && stats.followers_count !== undefined) {
                followersStat.textContent = stats.followers_count;
                followersStat.classList.add('updated');
                setTimeout(() => {
                    followersStat.classList.remove('updated');
                }, 300);
            }
        }

        // 查看用户信息功能
        async function viewUserInfo(userId) {
            try {
                const response = await fetch(`/user/get_user_info/?user_id=${userId}`);
                const result = await response.json();

                if (result.success) {
                    showUserInfoModal(result.user);
                } else {
                    showMessage('获取用户信息失败: ' + result.message, 'error');
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
                showMessage('获取用户信息失败，请重试', 'error');
            }
        }

        /**
         * 显示用户信息模态框
         * @param {Object} user - 用户对象
         */
        function showUserInfoModal(user) {
            // 确保头像URL是完整的
            const avatarUrl = ensureAbsoluteAvatarUrl(user.avatar);

            document.getElementById('modal-user-avatar').src = avatarUrl;
            document.getElementById('modal-user-avatar').onerror = function() {
                this.onerror = null;
                this.src = '{% static 'images/default-avatar.png' %}';
            };
            document.getElementById('modal-user-name').textContent = user.username;
            document.getElementById('modal-user-bio').textContent = user.bio;
            document.getElementById('modal-user-email').textContent = user.email;
            document.getElementById('modal-user-registration').textContent = user.registration_date;

            const interestsContainer = document.getElementById('modal-user-interests');
            if (user.interests && user.interests.length > 0) {
                interestsContainer.innerHTML = user.interests.map(interest =>
                    `<span class="interest-tag"><i class="fas fa-tag"></i>${interest}</span>`
                ).join('');
            } else {
                interestsContainer.innerHTML = '<span class="text-muted">暂无兴趣标签</span>';
            }

            const modal = new bootstrap.Modal(document.getElementById('userInfoModal'));
            modal.show();
        }

        /**
         * 编辑活动（示例函数）
         * @param {number} activityId - 活动ID
         */
        function editActivity(activityId) {
            showMessage('编辑功能开发中...', 'info');
            // 这里可以跳转到编辑页面或打开编辑模态框
            // window.location.href = `/meet/edit_activity/${activityId}/`;
        }

        /**
         * 取消报名
         * @param {number} activityId - 活动ID
         */
        async function cancelParticipation(activityId) {
            if (!confirm('确定要取消报名吗？取消后如需参加需要重新报名。')) {
                return;
            }

            try {
                const response = await fetch(`/user/cancel_participation/${activityId}/`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken')
                    }
                });

                const result = await response.json();

                if (result.success) {
                    showMessage(result.message, 'success');
                    // 重新加载参与活动列表
                    loadSectionData('joined-activities');

                    // 更新统计数字
                    updateStatsCounter('joined-activities', -1);
                } else {
                    showMessage(result.message, 'error');
                }
            } catch (error) {
                console.error('取消报名失败:', error);
                showMessage('网络错误，请重试', 'error');
            }
        }

        /**
         * 更新统计数字
         * @param {string} statType - 统计类型
         * @param {number} change - 变化量
         */
        function updateStatsCounter(statType, change) {
            const statItems = document.querySelectorAll('.stat-item');
            statItems.forEach(item => {
                if (item.getAttribute('data-target') === statType) {
                    const numberElement = item.querySelector('.stat-number');
                    const currentCount = parseInt(numberElement.textContent);
                    const newCount = Math.max(0, currentCount + change);

                    // 添加更新动画
                    numberElement.classList.add('updated');
                    numberElement.textContent = newCount;

                    // 移除动画类
                    setTimeout(() => {
                        numberElement.classList.remove('updated');
                    }, 300);
                }
            });
        }

        /**
         * 平滑移除用户卡片
         * @param {number} userId - 用户ID
         * @param {string} listType - 列表类型 ('following' 或 'followers')
         */
        function removeUserCard(userId, listType) {
            const card = document.getElementById(`${listType}-user-${userId}`);
            if (card) {
                card.classList.add('removing');
                setTimeout(() => {
                    if (card.parentNode) {
                        card.parentNode.removeChild(card);
                    }

                    // 更新列表标题中的数量
                    updateListCount(listType);
                }, 300);
            }
        }

        /**
         * 更新列表数量显示
         * @param {string} listType - 列表类型
         */
        function updateListCount(listType) {
            const section = document.getElementById(listType);
            if (!section) return;

            const title = section.querySelector('.section-title .badge');
            if (title) {
                const currentCount = parseInt(title.textContent);
                title.textContent = Math.max(0, currentCount - 1);
            }
        }
        // 图片加载错误处理函数
function handleImageError(img, defaultType = 'activity') {
    const defaultImages = {
        'activity': 'https://res.cloudinary.com/dqfqah1dn/image/upload/v1640997659/meetlocal/default-activity_zkvqjp.jpg',
        'avatar': 'https://res.cloudinary.com/dqfqah1dn/image/upload/v1640997659/meetlocal/default-avatar_qwq8xj.png'
    };

    console.log('图片加载失败:', img.src);

    // 移除错误处理器避免循环
    img.onerror = null;

    // 设置默认图片
    img.src = defaultImages[defaultType] || defaultImages['activity'];

    // 确保图片显示
    img.style.display = 'block';
}

// 头像加载错误处理
function handleAvatarError(img) {
    const parent = img.parentElement;
    const username = img.alt || 'User';

    if (parent && username) {
        // 显示用户名字首字母
        parent.innerHTML = username.charAt(0).toUpperCase();
        parent.style.background = 'linear-gradient(135deg, var(--primary), var(--secondary))';
        parent.style.color = 'white';
        parent.style.display = 'flex';
        parent.style.alignItems = 'center';
        parent.style.justifyContent = 'center';
        parent.style.fontWeight = '600';
    }

    // 隐藏损坏的图片
    img.style.display = 'none';
}

    </script>
</body>
</html>